package com.example.nfctagcommons.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.View;

import com.example.nfctagcommons.R;
import com.example.nfctagcommons.utils.StringPool;

@SuppressLint("NewApi")
public class LoadOnBackgroundDialog {
	private Activity activity;
	public LoadOnBackgroundDialog(Activity activity) {
		this.activity = activity;
	}
	public void load(boolean cancellable, String title, final IBackgroundAction backgroundAction){
		View loaderView = activity.getLayoutInflater().inflate(R.layout.simple_loader_layout, null);
		AlertDialog.Builder loader = new AlertDialog.Builder(activity);
		if (title != null && !title.equals(StringPool.BLANK)){
			loader.setTitle(title);
		}
		loader.setView(loaderView);
		loader.setCancelable(cancellable);
	    final Dialog loaderDialog = loader.create();
	    loaderDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
	    loaderDialog.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	    loaderDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface arg0) {
				backgroundAction.onCancelled();
			}
		});
	    loaderDialog.show();
		AsyncTask<Void, Void, Boolean> loginAsyncTask = new AsyncTask<Void, Void, Boolean>(){
			@Override
			protected Boolean doInBackground(Void... arg0) {
				return backgroundAction.doBackgroundAction();
			}
			@Override
			protected void onPostExecute(Boolean success) {
				loaderDialog.dismiss();
				backgroundAction.doPostExecuteAction(success);
			}
		};
		if (android.os.Build.VERSION.SDK_INT > 10) {
			loginAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			loginAsyncTask.execute();
		}
	}
	public interface IBackgroundAction{
		public boolean doBackgroundAction();
		public void doPostExecuteAction(boolean success);
		public void onCancelled();
	}
}
